package com.hzaccp.syncdbjava.window.biz;

import java.util.HashMap;
import java.util.Map;

import com.hzaccp.syncdbjava.entity.Column;
import com.hzaccp.syncdbjava.entity.Table;
import com.hzaccp.syncdbjava.helper.JavaCodeHelper;
import com.hzaccp.syncdbjava.helper.TypeMapping;
import com.hzaccp.syncdbjava.window.MainWindow;

/**
 * 实体类生成器
 * */
public class EntityBuilderBiz {
	public static void builder(MainWindow window, Map<String, Table> excelTables) {
		for (String tableKey : excelTables.keySet()) {
			Table table = excelTables.get(tableKey);

			//通过表名取得类[如:com.test.T_DB_pserson改为com.test.PsersonInfo]
			String className = JavaCodeHelper.getClassAllName(table.getPackName() + "." + table.getTableName());

			//初始化
			JavaCodeHelper codeFile = new JavaCodeHelper(className, false, table.getTableName_ch() + JavaCodeHelper.NEWLINE + "*" + className);

			codeFile.addConstructor(null);//默认构造方法
			Map<String, String> map = new HashMap<String, String>();
			map.put("id", "String");
			codeFile.addConstructor(map);//id构造方法

			//其他属性
			for (String key : table.getColumns().keySet()) {
				Column c = table.getColumns().get(key);
				String fk = c.getForeignKey();
				if (fk != null && fk.length() > 0 && !"null".equals(fk)) {//关联字段
					fk = fk.replace("[", "");
					String fks[] = fk.split("]");
					String fullType = JavaCodeHelper.getClassAllName(fks[0]);//类型
					codeFile.implortPage(fullType);//包入类型包
					String type = JavaCodeHelper.classNameSubPackage(fullType)[1];
					codeFile.addField("private", type, c.getFiledName(), ";");
					codeFile.insertDescription(c.getFiledName2(), true);//注释
					codeFile.addGetterAndSetter(c.getFiledName(), type);//get and set		
				} else {//普通字段
					String fullType = TypeMapping.sqlToJava(c.getFiledType());
					String type = JavaCodeHelper.classNameSubPackage(fullType)[1];
					codeFile.implortPage(fullType);//包入类型包
					codeFile.addField("private", type, c.getFiledName(), ";");
					codeFile.insertDescription(c.getFiledName2(), true);//注释
					codeFile.addGetterAndSetter(c.getFiledName(), type);//get and set
				}
			}

			try {
				codeFile.buider();//生成文件
				window.print("生成:" + className);
			} catch (Exception err) {
				err.printStackTrace();
			}
		}
	}

}
